//
//  LZReportProblemViewController.m
//  laziz_Consumer
//
//  Created by XMac on 16/10/31.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZReportProblemViewController.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "BlocksKit+UIKit.h"
#import "UIView+Rotation.h"
#import "LZReportProblemsPresenter.h"
#import "LZAlertView.h"
#import "LZRemindView.h"

static int MAX_LIMIT_NUMS = 1000;

@interface LZReportProblemViewController ()<UITextViewDelegate>
{
    NSString *kPlaceHolderString;
}
@property (strong, nonatomic) IBOutlet UITextView *reportTextView;

@property (copy, nonatomic) NSString *submitStr;

@property (strong, nonatomic) UIButton *nav_right_button;

@end

@implementation LZReportProblemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"意见反馈页面";
    
    kPlaceHolderString = LZLocalizedString(@"setting_report_characters_remind", nil);

    [self configUI];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - request

- (void)requestUploadReportProblem {
    
    if (self.submitStr.length == 0) {
        return;
    }
    
    self.nav_right_button.userInteractionEnabled = NO;

    WS(weakSelf)
    [LZReportProblemsPresenter reportProblemWithType:@"1" andContent:self.submitStr onSuccess:^(id data) {
        weakSelf.nav_right_button.userInteractionEnabled = YES;
        [LZRemindView initWithImage:[UIImage imageNamed:@"提示对勾"] andContent:LZLocalizedString(@"setting_report_submit_success_remind", nil)];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } onFail:^(NSString *fail) {
        weakSelf.nav_right_button.userInteractionEnabled = YES;
    }];
}

#pragma
#pragma mark Private method
-(void)configUI{
    self.title = LZLocalizedString(@"setting_report_problem", nil);
    
    WS(weakSelf)

    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 60, 40);
    
    UIImage *image_back = [UIImage imageNamed:@"lz_back_en"];
    [backButton setImage:image_back forState:UIControlStateNormal];
    backButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(backButton.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [backButton setLanguageRotaion];
    }
    
    [backButton bk_addEventHandler:^(id sender) {
        //返回action
        [weakSelf.reportTextView resignFirstResponder];
        [weakSelf navigationShouldPopOnBackButton];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [self navigationItemSetting:@[backButton] type:NAVIGATIONITEMSETTING_LEFT];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 60, 40);
    [button setTitle:LZLocalizedString(@"submit_min", nil) forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    [button sizeToFit];
    [button bk_addEventHandler:^(id sender) {
        //提交action
        [weakSelf requestUploadReportProblem];
    } forControlEvents:UIControlEventTouchUpInside];
    
    button.userInteractionEnabled = NO;
    
    self.nav_right_button = button;
    
    [self navigationItemSetting:@[button] type:NAVIGATIONITEMSETTING_RIGHT];

    
    _reportTextView.layer.borderColor = UIColorFromRGB(0xECECEC, 1).CGColor;
    _reportTextView.layer.borderWidth = 1;
    
    _reportTextView.layer.cornerRadius = 5;
    _reportTextView.layer.masksToBounds = YES;
    
    _reportTextView.text = kPlaceHolderString;
}

#pragma mark - event

- (void)navigationShouldPopOnBackButton {
    if (self.submitStr.length>0) {
        [self showPopAlert];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)showPopAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"setting_report_quit_remind", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        if (index == 1) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    };
}

#pragma
#pragma mark UITextViewDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView{
    
    if ([textView.text isEqualToString:kPlaceHolderString]) {
        textView.text = @"";
        textView.textColor = UIColorFromRGB(0x686868, 1);
    }
}


-(void)textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = kPlaceHolderString;
        textView.textColor = UIColorFromRGB(0xcecece, 1);
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    //获取高亮部分内容
    //NSString * selectedtext = [textView textInRange:selectedRange];
    
    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    if (selectedRange && pos) {
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        if (offsetRange.location < MAX_LIMIT_NUMS) {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = @"";
            //判断是否只普通的字符或asc码(对于中文和表情返回NO)
            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
            if (asc) {
                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
            }
            else
            {
                __block NSInteger idx = 0;
                __block NSString  *trimString = @"";//截取出的字串
                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个
                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                                         options:NSStringEnumerationByComposedCharacterSequences
                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                                          
                                          if (idx >= rg.length) {
                                              *stop = YES; //取出所需要就break，提高效率
                                              return ;
                                          }
                                          
                                          trimString = [trimString stringByAppendingString:substring];
                                          
                                          idx++;
                                      }];
                
                s = trimString;
            }
            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        }
        return NO;
    }
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    UITextRange *selectedRange = [textView markedTextRange];
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果在变化中是高亮部分在变，就不要计算字符了
    if (selectedRange && pos) {
        return;
    }
    
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum <1) {
        [self.nav_right_button setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
        self.nav_right_button.userInteractionEnabled = NO;
    }
    
    if (!self.nav_right_button.userInteractionEnabled && existTextNum >1) {
        self.nav_right_button.userInteractionEnabled = YES;
        [self.nav_right_button setTitleColor:UIColorFromRGB(0xeeeeee, 1) forState:UIControlStateNormal];

    }
    
    
    if (existTextNum > MAX_LIMIT_NUMS)
    {
        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        
        [textView setText:s];
    }
    
    self.submitStr = [textView.text copy];
    
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = self.submitStr.length==0;

    
}

@end
